package authority;

import po.User;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static java.util.Objects.isNull;

@WebFilter("/*")
public class LoginFilter extends HttpFilter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
      // 获取当前请求的路径，根据已知条件判断当前路径是否需要登陆
        HttpServletRequest request =(HttpServletRequest)req;
        HttpServletResponse response =(HttpServletResponse)res;
           String path= request.getRequestURI();
           // 正则表达式    xxxxxx/register-login.png

        // 如果我的路径包含下面任何一个字符串 那么不做登陆校验
        // 静态资源也要放行 页面验证码请求也要放行
        if(path.matches(".*/register.html.*")|| path.matches(".*/register/.*")|| path.matches(".*/css/.*")|| path.matches(".*/js/.*")||path.matches(".*/img/.*")){

        }else{
            // 校验当前用户是否已经登陆，如果已经登陆 啥也不干，如果没有登陆 ，页面跳转到登陆页面，并再页面显示请先登陆然后在做操作。
            // 用户登陆成功的时候，往session中设定了属性：loginUser  session.setAttribute("loginUser",user);
            HttpSession session = request.getSession();
            User user =(User) session.getAttribute("loginUser");
            if(user == null){// 说明用户没有登陆
                // 页面跳转到登陆页面
                request.getRequestDispatcher("/register.html").forward(request,response);
            }


        }
        chain.doFilter(request,response);


    }



}
